package com.zysdev.zysplayer

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.localbroadcastmanager.content.LocalBroadcastManager

import android.content.IntentFilter

import android.content.Intent

import android.content.BroadcastReceiver
import android.content.Context
import com.zysdev.zysplayer.service.PlayMusicService
import com.zysdev.zysplayer.utils.TimeUtil
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import com.zysdev.zysplayer.databinding.ActivityMain1Binding


public class MainActivity1 : AppCompatActivity(), View.OnClickListener {

    public lateinit var binding: ActivityMain1Binding

    //    private var player: ZYSPlayer? = null
    private var mMusicReceiver: MusicReceiver? = null

    //    private val mMusicDatas: List<MusicData> = ArrayList()
    private var totalTime = 0
    private var position = 0
    private var playState = false
    private var isFirstPlay = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMain1Binding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.ivPlayOrPause.setOnClickListener(this)
        binding.ivLast.setOnClickListener(this)
        binding.ivNext.setOnClickListener(this)
        binding.btnLeft.setOnClickListener(this)
        binding.btnRight.setOnClickListener(this)
        binding.btnCenter.setOnClickListener(this)
        binding.btnSpeed.setOnClickListener(this)
        binding.btnSpeedAdd.setOnClickListener(this)
        binding.btnPitch.setOnClickListener(this)
        binding.btnPitchAdd.setOnClickListener(this)
        binding.btnPitchSpeed.setOnClickListener(this)
        binding.musicSeekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                position = totalTime * progress / 100
                binding.tvCurrentTime.setText(TimeUtil.duration2Time(progress))
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {
//                Log.i(TAG, "onStopTrackingTouch: $position")
                seekTo(position)
            }
        })
        val intent = Intent(this, PlayMusicService::class.java)
//        intent.putExtra(PARAM_MUSIC_LIST, mMusicDatas as Serializable?)
        startService(intent)

        initMusicReceiver()
    }

    private fun initMusicReceiver() {
        mMusicReceiver = MusicReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(PlayMusicService.ACTION_STATUS_MUSIC_PLAY)
        intentFilter.addAction(PlayMusicService.ACTION_STATUS_MUSIC_PAUSE)
        intentFilter.addAction(PlayMusicService.ACTION_STATUS_MUSIC_DURATION)
        intentFilter.addAction(PlayMusicService.ACTION_STATUS_MUSIC_COMPLETE)
        intentFilter.addAction(PlayMusicService.ACTION_STATUS_MUSIC_PLAYER_TIME)
        /*注册本地广播*/LocalBroadcastManager.getInstance(this)
            .registerReceiver(mMusicReceiver!!, intentFilter)
    }

    inner class MusicReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent) {

            val action = intent.action
//            Log.e("---", "----action=$action")
            if (action == PlayMusicService.ACTION_STATUS_MUSIC_PLAY) {
                binding.ivPlayOrPause.setImageResource(R.drawable.ic_pause)
                val currentPosition =
                    intent.getIntExtra(PlayMusicService.PARAM_MUSIC_CURRENT_POSITION, 0)
                binding.musicSeekBar.progress = currentPosition
//                if (!mDisc.isPlaying()) {
//                    mDisc.playOrPause()
//                }
            } else if (action == PlayMusicService.ACTION_STATUS_MUSIC_PAUSE) {
                binding.ivPlayOrPause.setImageResource(R.drawable.ic_play)
//                if (mDisc.isPlaying()) {
//                    mDisc.playOrPause()
//                }
            } else if (action == PlayMusicService.ACTION_STATUS_MUSIC_DURATION) {
                val duration = intent.getIntExtra(PlayMusicService.PARAM_MUSIC_DURATION, 0)
                //                updateMusicDurationInfo(duration);
            } else if (action == PlayMusicService.ACTION_STATUS_MUSIC_COMPLETE) {
//                val isOver = intent.getBooleanExtra(PlayMusicService.PARAM_MUSIC_IS_OVER, true)
//                complete(isOver)
            } else if (action == PlayMusicService.ACTION_STATUS_MUSIC_PLAYER_TIME) {
                val currentTime = intent.getIntExtra("currentTime", 0)
                val totalTime = intent.getIntExtra("totalTime", 0)
                setCurrentTime(currentTime, totalTime)
            }
        }
    }

    override fun onClick(v: View?) {
        if (v == binding.ivPlayOrPause) {
            if (isFirstPlay) {
                isFirstPlay = false
                playState = true
                binding.ivPlayOrPause.setImageResource(R.drawable.ic_pause)
                play()
                return
            }
            playState = !playState
//            Log.i(TAG, "onClick: ---------$playState")
            if (playState) {
                binding.ivPlayOrPause.setImageResource(R.drawable.ic_play)
                pause()
//                mDisc.stop()
            } else {
                binding.ivPlayOrPause.setImageResource(R.drawable.ic_pause)
                resume()
//                mDisc.play()
            }
        } else if (v == binding.btnLeft) {
            left()
        } else if (v == binding.btnRight) {
            right()
        } else if (v == binding.btnCenter) {
            center()
        } else if (v == binding.ivNext) {
//            mDisc.next()
        } else if (v == binding.ivLast) {
//            mDisc.last()
        } else if (v == binding.btnSpeed) {
//            mDisc.last()
            optMusic(PlayMusicService.ACTION_OPT_MUSIC_SPEED)
        } else if (v == binding.btnSpeedAdd) {
//            mDisc.last()
            optMusic(PlayMusicService.ACTION_OPT_MUSIC_SPEED_ADD)
        } else if (v == binding.btnPitch) {
//            mDisc.last()
            optMusic(PlayMusicService.ACTION_OPT_MUSIC_PITCH)
        } else if (v == binding.btnPitchAdd) {
//            mDisc.last()
            optMusic(PlayMusicService.ACTION_OPT_MUSIC_PITCH_ADD)
        } else if (v == binding.btnPitchSpeed) {
//            mDisc.last()
            optMusic(PlayMusicService.ACTION_OPT_MUSIC_PITCH_SPEED_NORMAL)
        }
    }

    private fun play() {
        optMusic(PlayMusicService.ACTION_OPT_MUSIC_PLAY)
    }

    private fun pause() {
        optMusic(PlayMusicService.ACTION_OPT_MUSIC_PAUSE)
    }

    fun resume() {
        optMusic(PlayMusicService.ACTION_OPT_MUSIC_RESUME)
    }

    fun left() {
        optMusic(PlayMusicService.ACTION_OPT_MUSIC_LEFT)
    }

    fun right() {
        optMusic(PlayMusicService.ACTION_OPT_MUSIC_RIGHT)
    }

    fun center() {
        optMusic(PlayMusicService.ACTION_OPT_MUSIC_CENTER)
    }

    private fun stop() {
//        mIvPlayOrPause.setImageResource(R.drawable.ic_play)
//        mTvMusicDuration.setText(displayUtil.duration2Time(0))
//        mTvTotalMusicDuration.setText(displayUtil.duration2Time(0))
//        mSeekBar.setProgress(0)
    }

    private operator fun next() {
//        mRootLayout.postDelayed(
//            Runnable { optMusic(MusicService.ACTION_OPT_MUSIC_NEXT) },
//            DURATION_NEEDLE_ANIAMTOR
//        )
//        mTvMusicDuration.setText(displayUtil.duration2Time(0))
//        mTvTotalMusicDuration.setText(displayUtil.duration2Time(0))
    }

    private fun last() {
//        mRootLayout.postDelayed(
//            Runnable { optMusic(MusicService.ACTION_OPT_MUSIC_LAST) },
//            DURATION_NEEDLE_ANIAMTOR
//        )
//        mTvMusicDuration.setText(displayUtil.duration2Time(0))
//        mTvTotalMusicDuration.setText(displayUtil.duration2Time(0))
    }

    private fun complete(isOver: Boolean) {
//        if (isOver) {
//            mDisc.stop()
//        } else {
//            mDisc.next()
//        }
    }

    private fun optMusic(action: String) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(Intent(action))
    }

    private fun seekTo(position: Int) {
        val intent = Intent(PlayMusicService.ACTION_OPT_MUSIC_SEEK_TO)
        intent.putExtra(PlayMusicService.PARAM_MUSIC_SEEK_TO, position)
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }

    private fun setCurrentTime(currentTime: Int, totalTime: Int) {
        binding.musicSeekBar.progress = currentTime * 100 / totalTime;
        this.totalTime = totalTime
        binding.tvCurrentTime.text = TimeUtil.secondsToDateFormat(currentTime, totalTime)
        binding.tvTotalTime.text = TimeUtil.secondsToDateFormat(totalTime, totalTime)
    }


    override fun onDestroy() {
        super.onDestroy()
        optMusic(PlayMusicService.ACTION_OPT_MUSIC_RELEASE)

        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMusicReceiver!!)
    }

}